package cn.jdy.audit.service;

import java.util.List;
import java.util.Map;

import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.jdy.audit.entity.QqRecord;
import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.service.ConfService;

/**
 * @author daihu
 * @title : 产品操作实现
 */
@Service
public class QqRecordService extends BaseDao<QqRecord> {

	@Autowired
	private ConfService confService;

	/**
	 * 按条件查询
	 * 
	 * @return
	 */
	public List<QqRecord> query(QqRecord qqrecord, String... date) {
		if (qqrecord == null)
			return super.findAll();
		if (qqrecord.getiDisplayLength() > 0) {
			return super.find(createFilter(qqrecord,date),
					qqrecord.getiDisplayStart(), qqrecord.getiDisplayLength());
		}
		return super.find(createFilter(qqrecord,date));
	}

	public Long count(QqRecord qqrecord, String... date) {
		return super.count(createFilter(qqrecord,date));
	}

	/**
	 * 拼装条件
	 * 
	 * @param page
	 * @return
	 */
	private DetachedCriteria createFilter(QqRecord qqrecord, String... date) {
		DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
		if(!StringUtil.isNullOrEmpty(qqrecord.getKeywords())) { //后台管理用到这个地方
      if(!StringUtil.isNullOrEmpty(qqrecord.getKeyType())) {
        dc.add(Restrictions.like(qqrecord.getKeyType(), qqrecord.getKeywords().trim(),MatchMode.ANYWHERE));
      }else
        //TODO 添加模糊搜索
        ;
    }	System.out.println(date[0]);
		if (date.length > 1 && !StringUtil.isNullOrEmpty(date[0])
				&& !StringUtil.isNullOrEmpty(date[1])) {
			dc.add(Restrictions.between("createTime", date[0], date[1]));
		}System.out.println(DateUtil.parseDate(date[0]));
		if (!StringUtil.isNullOrEmpty(qqrecord.getQq_account())) {
			dc.add(Restrictions.like("qq_account", qqrecord.getQq_account(),MatchMode.ANYWHERE));
		}
		if (!StringUtil.isNullOrEmpty(qqrecord.getUser_ip())) {
			dc.add(Restrictions.like("user_ip", qqrecord.getUser_ip(),MatchMode.ANYWHERE));
		}
		
		if (!StringUtil.isNullOrEmpty(qqrecord.getState())) {
			dc.add(Restrictions.eq("state", qqrecord.getState()));
		}
		dc.addOrder(Order.desc("id"));
		return dc;
	}

	/**
	 * 
	 * @param productx
	 * @return
	 */
	public List<QqRecord> querypage(QqRecord qqrecord) {
		return super.find(createFilter(qqrecord),
				qqrecord.getPageNo(), 4);
	}

	/**
	 * 查询热门产品
	 * 
	 * @return
	 */
	public List<QqRecord> queryHot() {
		DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
		dc.addOrder(Order.desc("readTimes"));
		return super.find(dc, 0, 5);

	}

	/**
	 * 按照类型查询 产品
	 * 
	 * @return
	 */
	public List<QqRecord> findbytype(Long columnid, int firstResult,
			int maxResults, boolean isImg) {
		DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
		if (null != columnid) {
			dc.add(Restrictions.eq("columnId", columnid));
		}
		if (isImg) {// 是否有封面图片
			dc.add(Restrictions.ne("imgUrl", ""));
		}
		dc.addOrder(Order.desc("createTime"));
		return super.find(dc, firstResult, maxResults);
	}

	/**
	 * 按照大分类 查询产品
	 * 
	 * @return
	 */
	public List<QqRecord> findbyPid(Long pid, int firstResult, int maxResults,
			boolean isImg) {
		DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
		dc.createAlias("cv", "cv");
		if (isImg) {// 是否有封面图片
			dc.add(Restrictions.ne("imgUrl", ""));
		}
		if (null != pid) {
			dc.add(Restrictions.eq("cv.pid", pid));
		}
		dc.addOrder(Order.desc("createTime"));
		return super.find(dc, firstResult, maxResults);
	}
	
	/**
	 * qq图形显示获取数据  daihu
	 * @param qq_b
	 * @param minutes
	 * @param i
	 * @param state
	 * @param qq
	 * @param ip
	 * @return
	 */
	public List<Map> querytop1(String qq_b,int minutes,int i,String state,String qq,String ip) {
		String sql="";
		try {
			if((qq_b!="")&&(minutes!=0)){
				 sql = "select count(1) aa1,DATE_ADD(date_format('"+qq_b+"','%Y-%m-%d %H:%i:%s'),INTERVAL "+minutes+"*("+i+"-1) MINUTE) time1"
				 		+ " from qq_record where unix_timestamp(DATE_ADD(date_format('"+qq_b+"','%Y-%m-%d %H:%i:%s'),INTERVAL "+minutes+"*("+i+"-1) MINUTE))<add_time "
				 		+ "and unix_timestamp(DATE_ADD(date_format('"+qq_b+"','%Y-%m-%d %H:%i:%s'),INTERVAL "+minutes+"*"+i+" MINUTE)) >add_time";				 
			}else{
				sql = "select count(1) aa1,DATE_ADD(date_format(SUBSTR(now(),1,10),'%Y-%m-%d'),INTERVAL (60*4*("+i+"-1)) MINUTE) time1"
						+ " from qq_record where unix_timestamp(DATE_ADD(date_format(SUBSTR(now(),1,10),'%Y-%m-%d'),INTERVAL (60*4*("+i+"-1)) MINUTE))<add_time "
				 		+ "and unix_timestamp(DATE_ADD(date_format(SUBSTR(now(),1,10),'%Y-%m-%d'),INTERVAL (60*4*("+i+")) MINUTE)) >add_time";
			}	
			if(state!=""){
				 sql=sql+" and state = '"+state+"' ";
			 }
			 if(qq!=""){
				 sql=sql+" and qq_account like '%"+qq+"%' ";
			 }
			 if(ip!=""){
				 sql=sql+" and user_ip like '%"+ip+"%' ";
			 }
			//System.out.println(sql+"11111111");
			SQLQuery sqlQuery = em().createSQLQuery(sql);
			// 将查询寻结果转换为Map格式，解决多表查询或零散字段查询 映射取值问题
			sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
			return sqlQuery.list();
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "qq查询异常！", e);
		}
		return null;
	}
	
	/**
	 * 每次查询数据先把表里面createTime为null的记录同步add_time的时间
	 */
	public void updateSql(){
		String sql="update qq_record set createTime=FROM_UNIXTIME(add_time) where createTime is NULL";
		SQLQuery sqlQuery = em().createSQLQuery(sql);
		sqlQuery.executeUpdate();
	}
	
}
